<template>
  <div id="popup">
    <p>name:{{ cityName }}</p>
    <p>adcode:{{ adcode }}</p>
    <p>level:{{ level }}</p>
  </div>
  <div id="map"></div>
</template>
<script setup>
import { gaode } from '../libs/gaode'
import { onMounted, ref } from 'vue'
var cityName = ref('')
var adcode = ref('')
var level = ref('')
//基础图层
const style = new ol.style.Style({
  //边线颜色
  stroke: new ol.style.Stroke({
    color: '#000',
    width: 4,
  }),
  fill: new ol.style.Fill({
    color: 'rgba(255,255,255,0.7)',
  }),
  
})
const source = new ol.source.Vector({})
const layer = new ol.layer.Vector({
  source,
  style,
})
//高亮图层
const hightLightStyle = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: '#000',
    width: 5,
  }),
  fill: new ol.style.Fill({
    color: 'rgb(60, 126, 253)',
  }),
})
const hightLightSource = new ol.source.Vector({})
const hightLightLayer = new ol.layer.Vector({
  source: hightLightSource,
  style:hightLightStyle,
  // zIndex:20000
})
onMounted(() => {
  const map = new ol.Map({
    target: 'map',
    layers: [gaode],
    view: new ol.View({
      center: [114.3, 30.5],
      zoom: 4,
      projection: 'EPSG:4326',
    }),
  })
//添加图层
  map.addLayer(layer)
  map.addLayer(hightLightLayer)
  console.log(map.getLayers().getArray())
  //定时器+飞行视角+geojson数据加载
  setTimeout(() => {
    map.getView().animate({
      center: [114.3, 30.5],
      zoom: 8,
    })
    //加载geojson数据
    fetch('../../public/data/HuBei.json')
      .then((res) => res.json())
      .then((data) => {
        var res = new ol.format.GeoJSON().readFeatures(data)
        console.log(res)
        source.addFeatures(res)
      })
  }, 1000)
  map.on('click', function (e) {
    // 获取当前点击的点是否存在要素, 并返回
    // debugger
    const feature = map.forEachFeatureAtPixel(
      e.pixel,
      function (feature, layer) {
        return feature
      }
    )
    if (feature) {
      hightLightSource.clear()
      hightLightSource.addFeature(feature)
      cityName.value = feature.values_.name
      adcode.value = feature.values_.adcode
      level.value = feature.values_.level
      var location = feature.geometryChangeKey_.target.extent_
      var point1 = (location[2] + location[0]) / 2
      var point2 = (location[3] + location[1]) / 2
      console.log(point1)
      var position = [point1, point2]
      var pixel = map.getPixelFromCoordinate(position)
      $('#popup')
        .show(500)
        .css({ left: pixel[0] + 'px', top: pixel[1] - 80 + 'px' })
    }
  })
})
</script>

<style scoped>
#popup {
  width: 150px;
  height: 120px;
  border: 1px solid #666;
  border-radius: 30px;
  position: fixed;
  top: 10px;
  right: 10px;
  z-index: 200;
  background-color: #fff;
  padding: 10px;
  display: none;
}
#popup p {
  margin-block: 8px;
}
</style>
